package com.example.demo.controller;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.common.BaseResult;
import com.example.demo.jwt.JwtUtils;
import com.example.demo.mapper.UserMapper;

@RestController
public class LoginController {

	@Autowired
	private UserMapper userMapper;

	/**
	 * 登陆
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@PostMapping(value = "/login")
	public BaseResult login(String username, String password) {
		String realPassword = userMapper.getPassword(username);
		if (realPassword == null) {
			return new BaseResult(401, "用户名错误", null);
		} else if (!realPassword.equals(password)) {
			return new BaseResult(401, "用户密码错误", null);
		} else {
			return new BaseResult(200, "登陆成功", JwtUtils.createToken(username));
		}
	}

	/**
	 * 注销
	 * jwt这一块，想了一下，好像没办法注销，生成了令牌，令牌就可以一直有，这边也无法操作令牌，例如设置过期一类的
	 * 建议存到redis，设置过期，每次拦截器通过redis里拿令牌验证
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public BaseResult logout() {
		return new BaseResult(200, "无法注销", null);
	}

	@RequestMapping(path = "/unauthorized/{message}")
	public BaseResult unauthorized(@PathVariable String message) throws UnsupportedEncodingException {
		return new BaseResult(405, "信息：", message);
	}
}
